package com.wenyl.juc.thread;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * @author Swimming Dragon
 * @description: TODO
 * @date 2024年11月02日 11:33
 */
public class CreateThread {
    /**
     * 1.继承Thread类，Thread类实现了Runnable方法
     * 2.重写run方法
     * 3.调用start方法
     */
    public void createWithThread(){
        new Thread1().start();
    }

    /**
     * 1.实现Runnable接口
     * 2.重写run方法
     * 3.调用start方法
     */
    public void createWithRunnable(){
        new Thread(new Thread2()).start();
    }

    /**
     * callable支持线程执行完返回数据
     * 1.实现Callable接口
     * 2.重写call方法
     * 3.创建FutureTask类，FutureTask实现了RunnableFuture，RunnableFuture是Runnable的一个子类
     * 4.创建Thread类
     * 5.调用start方法
     */
    public void createWithCallable(){
        FutureTask<String> futureTask = new FutureTask<>(new Thread3());
        new Thread(futureTask).start();
        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * TimerTask实现了Runnable接口
     * 1.继承TimerTask抽象类
     * 2.重写run方法
     * 3.创建Timer类
     * 4.调用schedule方法
     */
    public void createWithTimerTask(){
        Thread4 thread4 = new Thread4();
        Timer timer = new Timer();
        timer.schedule(thread4,3000,2000);
    }

    /**
     * 1.Executors创建线程池
     * 2.创建任务提交线程池
     * 3.线程池执行完关闭
     */
    public void createWithExecutors(){
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for(int i=0;i<5;i++){
            executorService.submit(() -> {
                for(int j=0;j<10;j++){
                    System.out.println(Thread.currentThread().getName()+" "+ j);
                }
            });
        }
        executorService.shutdown();
    }
}

class Thread1 extends Thread{
    @Override
    public void run() {
        System.out.println("extends Thread");
    }
}
class Thread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("implements Runnable");
    }
}

class Thread3 implements Callable<String>{

    @Override
    public String call() throws Exception {
        System.out.println("implements Callable");
        return "我是callable";
    }
}

class Thread4 extends TimerTask{
    @Override
    public void run() {
        System.out.println("extends TimerTask");

    }
}